<?php
class JwtHandler
{
	private $secretKey;

	public function __construct()
	{
		$this->secretKey = 'your-secret-key'; // 应该使用更安全的密钥
	}

	//	生成令牌
	public function generateToken($userId)
	{
		$header = json_encode(['typ' => 'JWT', 'alg' => 'HS256']);
		$payload = json_encode([
			'user_id' => $userId,
			'iat' => time(),
			'exp' => time() + (60 * 60) // 1小时过期
		]);

		$base64Header = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($header));
		$base64Payload = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($payload));

		$signature = hash_hmac('sha256', $base64Header . "." . $base64Payload, $this->secretKey, true);
		$base64Signature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));

		return $base64Header . "." . $base64Payload . "." . $base64Signature;
	}

	// 验证令牌
	public function validateToken($token)
	{
		$parts = explode('.', $token);

		if (count($parts) !== 3) {
			return false;
		}

		$signature = hash_hmac('sha256', $parts[0] . "." . $parts[1], $this->secretKey, true);
		$base64Signature = str_replace(['+', '/', '='], ['-', '_', ''], base64_encode($signature));

		return hash_equals($base64Signature, $parts[2]);
	}
}
?>